﻿using Business.Service;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcAppWeb.Controllers
{
    public class FileManageController : BaseDataController
    {
        //
        // GET: /FileManage/

        public ActionResult FileManage()
        {
            if (Session["UserInfo"] == null) return RedirectToAction("LogOn", "Account");
            else
            {
                AppUserList model = (AppUserList)Session["UserInfo"];
                return View(model);

            }
        }

        ///<summary>
        ///查询日志类型
        ///</summary>
        ///<returns></returns>
        public JsonResult InitJsonResult(string systemID, string modularID)
        {
            string where = "  where 1=1 ";
            int page = int.Parse(Request["page"].ToString());
            int rows = int.Parse(Request["rows"].ToString());
            int total = 0;
            if (systemID != "" && systemID != "0")
            {
                where += " and t1.systemID=" + systemID;
            }
            if (modularID != "" && modularID != "0")
            {
                where += " and t1.modularID=" + modularID;
            }

            var retData = new object();
            BFileManage db = new BFileManage();
            retData = db.GetOAFileManageInfo(page, rows, out total, where).ToList();
            Dictionary<string, object> json = new Dictionary<string, object>();
            json.Add("total", total);
            json.Add("rows", retData);
            return Json(json);
        }



        [HttpPost]
        public string SaveData()
        {
            string sjson = string.Empty;
            AppUserList model = (AppUserList)Session["UserInfo"];
            try
            {
                int systemID = Convert.ToInt32(Request["ssystemName"].ToString());
                int modularID = Convert.ToInt32(Request["smodularName"].ToString());
                string fileType = Request["fileType"].ToString();
                string fileRemarks = Request["txtFileRemarks"].ToString();

                string url = GetUrlInfo(systemID, modularID);
                if (url == "")
                {
                    return sjson = "{success:false,msg:'请配置上传系统路径！'}"; ;
                }
                HttpPostedFileBase file = Request.Files["uploadfile"];
                DataTable table = new DataTable();
                string importStr = string.Empty;
                string fileFormat = string.Empty;
                string imfileName = string.Empty;
                sjson = OAImportFile(file, url, out importStr, out fileFormat, out imfileName);
                if (!string.IsNullOrEmpty(sjson))
                    return sjson;
                BFileManage bfm = new BFileManage();
                OAFileManage fm = new OAFileManage();
                fm.SYSTEMID = Convert.ToInt32(systemID);
                fm.MODULARID = Convert.ToInt32(modularID);
                fm.FILEURL = importStr;
                fm.FILEREMARKS = fileRemarks;
                fm.FILEFORMAT = fileFormat;
                fm.FILETYPE = fileType;
                fm.USERCODE = model.USERCODE;
                fm.FILENAME = imfileName;
                int n = bfm.InsertOAFileManage(fm);
                if (n > 0)
                {
                    sjson = "{success:true}";
                }
                else
                {
                    sjson = "{success:false,msg:'上传失败！'}";
                }
            }
            catch (Exception)
            {

                sjson = "{success:false,msg:'系统和模块必须选择！'}";
            }
            System.Threading.Thread.Sleep(2000);
            return sjson;
        }


        private string GetUrlInfo(int systemID, int modularID)
        {
            BFileManage bfm = new BFileManage();
            string url = "";
            List<OAFileSystem> listSystem = bfm.GetFileSystemInfo(systemID);
            List<OAFileModular> listModular = bfm.GetFileModularInfo(modularID);
            if (listSystem.Count == 0 || listModular.Count == 0)
            {
                url = "";
            }
            else
            {
                url = "upload" + "/" + listSystem[0].FILEURL + "/" + listModular[0].FILEURL;

            }

            return url;
        }

        [HttpPost]
        //流方式下载
        public void Download(string url, string fileName)
        {
            string filePath = Server.MapPath("../" + url);//路径

            //以字符流的形式下载文件
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment;   filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            ;
        }

        //流方式下载
        public string GetUrl(string url)
        {
            string filePath = Server.MapPath("../" + url);//路径
            string sjson = "";
            sjson = filePath;
            return sjson; ;
        }
    }
}
